#include <iostream>
#include <string>
#include <cstring>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

enum
{
    USE_ERR,
    SOCKET_ERR,
    BIND_ERR,
    CONNECT_ERR
};

void Useage(const std::string& str)
{
    std::cout <<"Useage:\n\t" << str << " ip port \n";
    exit(USE_ERR);
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Useage(argv[0]);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cout << "socket create success\n";
        exit(SOCKET_ERR);
    }

    struct sockaddr_in server;
    bzero(&server, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    int n = ::connect(sockfd, reinterpret_cast<struct sockaddr*>(&server), sizeof server);
    if(n < 0)
    {
        std::cout << "connect error\n";
        exit(CONNECT_ERR);
    }
    std::cout << "connect success\n";
    
    while(true)
    {
        //1. 获取输入
        std::string message;
        std::cout << "Please input# ";
        std::getline(std::cin, message);
        
        // 2.发送数据
        ssize_t n = ::send(sockfd, message.c_str(), message.size(), 0);
        if(n < 0)
        {
            std::cout << "send error\n";
            continue;
        }

        // 3.接受结果
        char buff[1024];
        n = ::recv(sockfd, buff, sizeof(buff) - 1, 0);
        if(n > 0)
        {
            // 4.打印结果
            buff[n] = 0;
            std::cout << "server say #" << buff << std::endl;
            // sleep(1);
        }
        else if(n == 0)
        {
            std::cout << "server is quit, me too!!!\n";
            break;
        }
        else
        {
            std::cout << "recv error\n";
            break;;
        }

    }


    return 0;
}
